import re
import pprint
import os
import datetime
from datetime import date
import time

from psn_django import *
from psn_web import psnWeb

class psnGame:

	def __init__(self):
		self.psn_web = psnWeb()

	def newGameTropy(self, game_db, GAME_TROPHY_LIST, force=False, j=1):
		k=1
		l=1
		hidden_id = 0
		trophy_id = 0
		for TROPHY in GAME_TROPHY_LIST:

			try:
				name = TROPHY["name"]
				detail = TROPHY["desc"]
			except:
				pass

			if TROPHY.has_key('id'):
				hidden_id = 0
				hidden = 0
				trophy_id = TROPHY["id"]
			else:
				if TROPHY["type"].upper() == "HIDDEN":
					name = "Hidden id (%2d-%2d)" %(k, j)
					detail = "Hidden Trophy"
					pic_url = "hidden.png"

					hidden_id = k
					trophy_id = 0
					hidden = 1
					k += 1
				else:
					hidden_id = 0
					trophy_id = l
					hidden = 0
					l += 1

					try:
						name = TROPHY["name"]
						detail = TROPHY["desc"]
					except:
						pprint.pprint(TROPHY)
						print "FUCK!"
						os._exit(0)

			pic_url = self.psn_web.download_trophy_image(game_db.psn_id, TROPHY, j, force)

			game_trophy_info_db = db.gameTrophyInfo.objects.filter(game=game_db, hidden_id=hidden_id, total_id=j, trophy_id=trophy_id)

			if len(game_trophy_info_db) is 0:
				print "New Trophy |%s| |%s|" %(name, detail)

				if TROPHY.has_key("id"):
					total = TROPHY["id"]
				else:
					total = j

				game_trophy_info_db = db.gameTrophyInfo(
						game = game_db,
						name = name,
						desc = detail,
						type = TROPHY["type"].lower(),
						hidden_id = hidden_id,
						total_id  = total,
						trophy_id = trophy_id)

				if pic_url is not None:
					game_trophy_info_db.pic_url = pic_url

				game_trophy_info_db.save()

			j += 1

	def newGame(self, game):
		print "New game found: %s" %game["psn_id"]

		game_db = db.gameInfo(psn_id  = game["psn_id"])

		if game.has_key("name"):
			print "Name: %s" %game["name"]
			game_db.name = game["name"]

		if game.has_key("publisher"):
			print "Publisher: %s" %game["publisher"]
			game_db.publisher = game["publisher"]

		if game.has_key("developer"):
			print "Developer: %s" %game["developer"]
			game_db.developer = game["developer"]

		if game.has_key("release_date"):
			print "Release: %s" %game["release_date"]

			try:
				format = '%B %d, %Y'
				date = datetime.datetime(*time.strptime(game["release_date"], format)[0:5])
				game_db.release_date = date
			except:
				print "Unknown format |%s|" %release_date

		if game.has_key("pic_url"):
			self.psn_web.download_game_image(game)

		game_db.save()

		return game_db
  
	def getGame(self, game, user=False):

		game_db = db.gameInfo.objects.filter(psn_id=game["psn_id"])

		if len(game_db) is 0:

			game_db = self.newGame(game)
	
			if user is not False:
				if game.has_key("card_id"):
					pass
				else:
					TROPHY = self.psn_web.get_user_game_info(user, game["psn_id"])
					self.newGameTropy(game_db, TROPHY, force=True)

		else:
			game_db = game_db[0]

		return game_db

	def fillGamesTrophy(self, psn_id, user):

		# Vamos tentar achar um USER que tenha PLATINA
		# Assim a lista nunca estara errada
		user_plt = self.psn_web.get_platinum_user_game(psn_id)

		if user_plt:
			user = user_plt

		game = {}
		game["psn_id"] = psn_id
		game_db = self.getGame(game)
		TROPHY = self.psn_web.get_user_game_info(user, psn_id)

		# Apaga os dados existentes
		self.newGameTropy(game_db, TROPHY, force=True)

if __name__ == '__main__':

	psn_game = psnGame()

	try:
		user = sys.argv[1]
		game = sys.argv[2]
		psn = True
	except:
		psn = False

	if psn is True:

		GAME = {}
		GAME["psn_id"] = game
		game_db = psn_game.getGame(GAME)

		print game_db.psn_id,game_db.name

		# - Precisamos apagar todos os registros de trofeu deste jogo
		# Informacoes dos users
		db.gameUserTrophyInfo.objects.filter(trophy__game=game_db).delete()
		# Informacoes proprias
		db.gameTrophyInfo.objects.filter(game=game_db).delete()
		# Informacoes dos jogos dos users
		db.userGameInfo.objects.filter(game=game_db).delete()

		# Recria os dados
		psn_game.fillGamesTrophy(GAME["psn_id"], user)

	else:
		GAME_LIST = get_all_game_list()

		for GAME in GAME_LIST:
			GAME = psn_game.psn_web.get_game_info(GAME)
			psn_web.download_game_image(GAME)

			GAME_TROPHY_LIST = []

			TROPHY = psn_web.get_game_trophy_list_ps3trophies(GAME)

			game_db = psn_game.getGame(GAME)
			psn_game.setGameTrophy(game_db, TROPHY)
